<template>
  <el-config-provider :locale="zhCn">
    <div class="friend-verify">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="success" @click="handleCreateVerify">新增信息</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="verifyList" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="message" label="验证消息" min-width="300" show-overflow-tooltip />
          <el-table-column prop="createBy" label="创建人" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="updateBy" label="更新人" width="120" />
          <el-table-column prop="updateTime" label="更新时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增/编辑验证信息对话框 -->
      <el-dialog
        v-model="verifyDialogVisible"
        :title="dialogType === 'create' ? '新增验证信息' : '编辑验证信息'"
        width="500px"
        destroy-on-close
        class="verify-dialog"
      >
        <el-form :model="verifyForm" label-width="100px" class="verify-form" :rules="formRules" ref="formRef">
          <el-form-item label="验证消息" prop="message" required>
            <el-input v-model="verifyForm.message" type="textarea" :rows="4" placeholder="请输入验证消息内容" maxlength="200" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="verifyDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitVerify">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import {
  getAuthenticationList,
  addAuthentication,
  updateAuthentication,
  deleteAuthentication,
  type AuthenticationInfo,
  type AuthenticationQueryParams,
  type PageResult
} from '@/api/userRate/friendVerify';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 筛选表单
const filterForm = reactive({
  message: ''
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '验证消息',
    prop: 'message',
    type: 'input',
    placeholder: '请输入验证消息'
  }
]);

// 表单验证规则
const formRules: FormRules = {
  message: [
    { required: true, message: '请输入验证消息', trigger: 'blur' },
    { max: 200, message: '验证消息不能超过200个字符', trigger: 'blur' }
  ]
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const verifyList = ref<AuthenticationInfo[]>([]);

// 获取用户信息
const userInfo = ref(localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')!) : {});

// 加载状态
const loading = ref(false);

// 对话框相关
const verifyDialogVisible = ref(false);
const dialogType = ref<'create' | 'edit'>('create');
const formRef = ref<FormInstance>();
const verifyForm = reactive<AuthenticationInfo>({
  account: '',
  message: ''
});

// 查询方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;
    const params: AuthenticationQueryParams = {
      account: userInfo.value.username || '',
      message: searchData.message || undefined,
      current: currentPage.value,
      size: pageSize.value
    };

    // 移除所有 undefined 的参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof AuthenticationQueryParams] === undefined) {
        delete params[key as keyof AuthenticationQueryParams];
      }
    });

    const res = (await getAuthenticationList(params)) as unknown as ApiResponse<PageResult<AuthenticationInfo>>;
    if (res.code === 200) {
      verifyList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('搜索失败：', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.message = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 初始化数据
const initData = async () => {
  loading.value = true;
  try {
    const params: AuthenticationQueryParams = {
      account: userInfo.value.username || '',
      current: currentPage.value,
      size: pageSize.value
    };
    const res = (await getAuthenticationList(params)) as unknown as ApiResponse<PageResult<AuthenticationInfo>>;
    if (res.code === 200) {
      verifyList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('初始化数据失败：', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 新增验证信息
const handleCreateVerify = () => {
  dialogType.value = 'create';
  verifyForm.id = undefined;
  verifyForm.account = userInfo.value.username || '';
  verifyForm.message = '';
  verifyDialogVisible.value = true;
};

// 编辑验证信息
const handleEdit = (verify: AuthenticationInfo) => {
  dialogType.value = 'edit';
  Object.assign(verifyForm, {
    id: verify.id,
    account: verify.account,
    message: verify.message
  });
  verifyDialogVisible.value = true;
};

// 删除验证信息
const handleDelete = async (verify: AuthenticationInfo) => {
  if (!verify.id) return;

  try {
    await ElMessageBox.confirm('确定要删除该验证信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 删除接口需要传id和account
    const res = (await deleteAuthentication({ id: verify.id!, account: userInfo.value.username || '' })) as unknown as ApiResponse;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      handleSearch();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 提交验证信息
const submitVerify = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 确保账号字段使用当前用户的username，只保留必要参数
    const { ...rest } = verifyForm;
    const submitData = {
      ...rest,
      account: userInfo.value.username || ''
    };

    if (dialogType.value === 'create') {
      const res = (await addAuthentication(submitData)) as unknown as ApiResponse;
      if (res.code === 200) {
        ElMessage.success('创建成功');
        verifyDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } else {
      if (!submitData.id) {
        ElMessage.error('缺少ID信息');
        return;
      }
      const res = (await updateAuthentication(submitData as AuthenticationInfo & { id: number })) as unknown as ApiResponse;
      if (res.code === 200) {
        ElMessage.success('更新成功');
        verifyDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    }
  } catch (error) {
    console.error('提交失败：', error);
    ElMessage.error('操作失败');
  }
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.message = val.message || '';
};

// 初始化
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.friend-verify {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    .custom-pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }

      :deep(.el-pagination__sizes) {
        margin-right: 16px;
      }
    }
  }
}

.verify-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .verify-form {
    .el-form-item {
      margin-bottom: 22px;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
</style>
